<?php

namespace Form;

use App\Dao\Settings\SettingsTaskTopDao;
use App\Dao\System\SystemConfigClassifyDao;
use Yj\Apidog\Annotation\ApiController;
use Yj\Apidog\Annotation\FormData;
use Yj\Apidog\Annotation\PostApi;
use Yj\ColumnBuilder\Column;
use Yj\Form\Elm;




/**
 * @ApiController(prefix="form/SystemConfigClassify")
 */
class SystemConfigClassify extends BaseForm
{
    protected $yjCode = 'config_classify';

    protected $routes = [
        'lists'=>'/admin/config_classify/lists',
        'add'=>'/admin/config_classify/add',
        'edit'=>'/admin/config_classify/edit',
        'form'=>'/form/SystemConfigClassify/update',
    ];

    public function getColumn(){
        $colum = Column::create();
        $colum->setRules([
            Column::txt()->setLabel('分类名称')->setProp('name'),
            Column::txt()->setLabel('分类key')->setProp('key'),
            Column::txt()->setLabel('描述')->setProp('info'),
            Column::txt()->setLabel('状态')->setProp('status'),
        ]);
        return $colum->toArray();
    }

    protected function getRoute($types=null){
        if(is_null($types)){
            return $this->routes;
        }
        return $this->routes[$types];
    }

    /**
     * @PostApi(path="config",description="配置")
     */
    public function config(){
        $routes =  $this->getRoute();
        $column = $this->getColumn();
        _SUCCESS(compact('routes','column'));
    }

    /**
     * @PostApi(path="update",description="添加")
     * @FormData(key="id",default=0)
     */
    public function update(){
        $id = $this->getValidatorData('id');
        $form = Elm::createForm($this->getRoute($id ? 'edit' : 'add'));
        $form->setRule([
            Elm::select('pid','上级分类')->required()->options(function (){
                $formData = App(SystemConfigClassifyDao::class)->where('pid', 0)->get();
                $formData->transform(function ($item){
                   return [
                       'label'=>$item['name'],
                       'value'=>$item['id'],
                   ];
                });
                $formData->prepend(['label'=>'无','value'=>0]);
                return $formData->toArray();
            }),
            Elm::input('name', '分类名称')->required(),
            Elm::input('key', 'key')->required(),
            Elm::input('info', '描述')->required(),
            Elm::number('sort', '排序')->required(),
            Elm::switches('status', '状态')
                ->activeValue(1)->inactiveValue(0)->required(),
        ]);
        $id && $form->append(
            Elm::hidden('id', $id)
        );
        $lists = $form->setTitle(($id ? '编辑' : '添加') . '分类')->formData(function () use ($id) {
            $formData = [];
            if ($id) {
                $formData = App(SystemConfigClassifyDao::class)->where('id', $id)->first();
            }
            return $formData;
        });
        _SUCCESS(formToData($lists));
    }


}